import java.awt.Color;
import java.awt.Graphics;
import java.util.LinkedList;

import javax.swing.BorderFactory;
import javax.swing.JPanel;

public class GamePanel extends JPanel {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Snake snake;

	public GamePanel(Snake snake) {
		this.snake = snake;
		setSize(Node.WIDTH * 25, Node.HEIGHT * 25);
		setBackground(new Color(0xE0EEE0));
		setBorder(BorderFactory.createLoweredBevelBorder());
	}

	@Override
	public void paint(Graphics g) {
		super.paint(g);
		//创建开始开始蛇体
		LinkedList<Node> body = snake.getBody();
		Color color = Color.RED;
		for (Node node : body) {
			g.setColor(color);
			g.fill3DRect(node.getX(), node.getY(), Node.WIDTH, Node.HEIGHT, true);
			color = color.getRGB() == Color.RED.getRGB() ? Color.BLACK : Color.RED;
		}
        
		//创建食物
		Color color1 = Color.BLUE;
		g.setColor(color1);
		g.fill3DRect(snake.getFood().getX(), snake.getFood().getY(), Node.WIDTH, Node.HEIGHT, true);
	}

	public void gameStart() {
		new Thread(new Runnable() {

			@Override
			public synchronized void run() {
				// TODO Auto-generated method stub
				while (true) {
					//当isquit为true时停止该线程
					if (snake.getIsquit()) {
						return;
					}
	                
					//启动身体移动和食物方法
					snake.nodeMove();
					snake.eatFood(); 
					//如果iseat为true，那么制造一个新的食物
					if (snake.getIseat()) snake.makeFood();
					repaint();
                    System.out.println("gamePanel线程:" + Thread.currentThread().getName());
					try {
						Thread.sleep(snake.getSpend());
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}).start();
	 }
}
